#!/bin/sh /etc/rc.common

START=99
STOP=99

USE_PROCD=1
PACKAGE_NAME=chirpstack

conf_rule_network() {
	local cfg="$1"
	local net_id

	config_get net_id $cfg net_id

	cat >> /var/etc/$PACKAGE_NAME/$PACKAGE_NAME.toml <<- EOF
		[network]
		net_id="$net_id"
		enabled_regions=[]
	EOF

	config_list_foreach $cfg enabled_regions config_rule_network_enabled_regions
}

config_rule_network_enabled_regions() {
	local region="$1"
	sed -i "s/enabled_regions=\[\(.*\)\]/enabled_regions=\[\1\"$region\",\]/" /var/etc/$PACKAGE_NAME/$PACKAGE_NAME.toml
	cp /etc/$PACKAGE_NAME/region_$region.toml /var/etc/$PACKAGE_NAME

	sed -i "s/\$MQTT_BROKER_HOST/localhost/" /var/etc/$PACKAGE_NAME/*.toml
	sed -i "s/\$POSTGRESQL_HOST/localhost/" /var/etc/$PACKAGE_NAME/*.toml
	sed -i "s/\$REDIS_HOST/localhost/" /var/etc/$PACKAGE_NAME/*.toml
}

configuration() {
	mkdir -p /var/etc/$PACKAGE_NAME
	rm -rf /var/etc/$PACKAGE_NAME/*.toml
	echo "" > /var/etc/$PACKAGE_NAME/$PACKAGE_NAME.toml

	cat >> /var/etc/$PACKAGE_NAME/$PACKAGE_NAME.toml <<- EOF
		[gateway]
		allow_unknown_gateways=true

		[integration]
		enabled = [
			"mqtt",
		]

		[integration.mqtt]
		json=true
		server="tcp://127.0.0.1:1883/"
	EOF

	config_load "$PACKAGE_NAME"
	config_foreach conf_rule_network "network"
}

start_service() {
	configuration

	procd_open_instance
	procd_set_param command /usr/bin/$PACKAGE_NAME -c /var/etc/$PACKAGE_NAME
	procd_set_param respawn 3600 5 -1
	procd_set_param file /etc/config/$PACKAGE_NAME /etc/config/chirpstack-concentratord
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "$PACKAGE_NAME" "/etc/config/chirpstack-concentratord"
}

reload_service() {
	stop
	start
}